package com.tang.framework.component.security;

import com.alibaba.fastjson.JSON;
import com.tang.common.constant.HttpStatus;
import com.tang.common.utils.ServletUtil;
import com.tang.framework.core.domain.HttpResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * @author tang jun liang
 * @Date 2023/2/10 15:00
 */
@Component
public class UnauthorizedHandler implements AuthenticationEntryPoint , Serializable {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        int code = HttpStatus.UNAUTHORIZED;
        String msg = String.format("请求访问：%s，认证失败，无法访问系统资源", request.getRequestURI());
        ServletUtil.renderString(response, JSON.toJSONString(HttpResult.error(code, msg)));
    }
}
